package springcloud.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springcloud.entity.Member;
import springcloud.entity.Result;
import springcloud.service.MemberOpenFeignService;

import javax.annotation.Resource;

@SuppressWarnings("all")
@RestController
@Slf4j
public class MemberNacosConsumerController {

    //定义一个基础的地址，用于拼接
    //http://member-service-nacos-provider 就是服务注册到 Nacos server的服务名，这里是小写
    private static final String MEMBER_SERVICE_NACOS_PROVIDER_URL = "http://member-service-nacos-provider";

    //配置RestTemplate
    @Resource
    private RestTemplate restTemplate;

    //注入配置的OpenFeign接口
    @Resource
    private MemberOpenFeignService memberOpenFeignService;

    //编写方法，通过OpenFeign完成远程调用
    @GetMapping("/member/openfeign/consumer/query/{id}")
    public Result<Member> queryMemberOpenfeignById(@PathVariable("id") Long id) {
        //使用openfeign接口方式远程调用
        log.info("调用方式是 openfeign..");
        return memberOpenFeignService.queryMemberById(id);
    }

    //方法/接口1. 添加member
    @PostMapping("/member/nacos/consumer/save")
    public Result<Member> save(Member member) {

        return restTemplate.postForObject(MEMBER_SERVICE_NACOS_PROVIDER_URL
                + "/member/save", member, Result.class);
    }

    //方法/接口2, 查询member
    @GetMapping("/member/nacos/consumer/query/{id}")
    public Result<Member> getMemberById(@PathVariable("id") Long id) {

        return restTemplate.getForObject(
                MEMBER_SERVICE_NACOS_PROVIDER_URL + "/member/query/" + id, Result.class);
    }
}
